package com.djinfo.work.controller;

import com.djinfo.work.common.anno.Log;
import com.djinfo.work.common.bean.AjaxJson;
import com.djinfo.work.common.util.StringUtil;
import com.djinfo.work.entity.TbSysRoleUser;
import com.djinfo.work.entity.TbSysRoles;
import com.djinfo.work.entity.TbSysUsers;
import com.djinfo.work.service.MenuService;
import org.openxmlformats.schemas.spreadsheetml.x2006.main.UsersDocument;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;


import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;

/**
 * @author wxf 描述： 用户Controller 实现登录 首页导航
 */
@Controller
@RequestMapping("/user")
public class UserController {
	private static final Log log = null;
	/**
	 * 自动注入
	 */
	@Autowired
	private com.djinfo.work.service.UserService UserService;
	@Autowired
	private com.djinfo.work.service.RoleService RoleService;
	@Autowired
	private MenuService menuService;


	/**
	 * 用户信息主表实体类
	 */
	private TbSysUsers tbSysUsers;

	
	/**
	 * 用户登录
	 * 
	 * @param username
	 *            账号
	 * @param password
	 *            密码
	 * @param authCode
	 *            验证码
	 * @return
	 *//*
	@Login(action= Action.Skip)
	@ResponseBody
	@RequestMapping("/login.do")
	public JSONObject login(String username, String password, String authCode, 
			HttpSession session, 
			HttpServletRequest request) {
		// json格式
		JSONObject data = new JSONObject();
		// 将map存入json格式中 返回前台
		Map<String, Object> result = new HashMap<String, Object>();
		// 查询用户ID
		Integer wdUser = UserService.getUserID(username, password);
		// 如果用户不存在，则返回0
		if (wdUser == 0) {
			// 登录失败的返回信息
			data.put("resultcode", 203);
			data.put("reason", "用户名或者密码错误");
			return data;
		}
		// 获取验证码
		String sRand = (String) session.getAttribute("randCheckCode");
		if(sRand==null||sRand==""){
			data.put("resultcode", 204);
			data.put("reason", "验证码错误");
			return data;
		}
		// 转换大小写
		String sRands = sRand.toLowerCase();
		// 转换大小写
		String authCodes = authCode.toLowerCase();
		if (!sRands.equals(authCodes)) {
			data.put("resultcode", 205);
			data.put("reason", "验证码错误");
			return data;
		}
		// 用户验证通过
		if (wdUser > 0) {
			// 存储数据与前台交互
			tbSysUsers = UserService.get(wdUser);
			data.put("resultcode", 200);
			data.put("reason", "登陆成功");
			data.put("token", "xxxxxxx");
			result.put("userID", tbSysUsers.getPkUserId());
			result.put("username", tbSysUsers.getUserName());
			result.put("headImg", "images/user.jpg");
			data.put("result", result);
			// 给session赋值
			if (session.getAttribute("users") != null) {
				// 如果session有值 就删掉重新保存
				session.removeAttribute("users");
				session.setAttribute("users", tbSysUsers.getPkUserId());
			} else {
				// 如果没有值，就保存用户id
				session.setAttribute("users", tbSysUsers.getPkUserId());
			}
			
		}
		return data;
	}
	
	private static void copyUserInfo(ServletContext servletContext) {
		try {
			ApplicationContext ac = WebApplicationContextUtils.getRequiredWebApplicationContext(servletContext);
			UserService userService = (UserService) ac.getBean("UserService");
			//
			Configuration configuration = Configuration.getInstance();
			String driverName = configuration.getProperty("sso.jdbc.driver").trim();
	      	String connName = configuration.getProperty("sso.jdbc.url").trim();
			//
	      	Map<String, Map<String, String>> map = new HashMap<String, Map<String, String>>(); // key - LNAME
	      	Class.forName(driverName);
	      	Connection con = DriverManager.getConnection(connName, configuration.getProperty("sso.jdbc.username").trim(), configuration.getProperty("sso.jdbc.password").trim());
	      	try {
				String sql = "select LNAME, UNAME from TB_HS_URM_USER";
				PreparedStatement ps = con.prepareStatement(sql);
				try {
					ResultSet rs = ps.executeQuery();
					if (rs != null) {
						try {
							while (rs.next()) {
								Map<String, String> user = new HashMap<String, String>();
								//
								user.put("LNAME", rs.getString("LNAME"));
								user.put("UNAME", rs.getString("UNAME"));
								//
								map.put(rs.getString("LNAME"), user);
							}
						} finally {
							rs.close();
						}
					}
				} finally {
					ps.close();
				}
			} finally {
				con.close();
			}
	      	
	      	List<TbSysUsers> users = userService.getAllUser();
	      	Map<String, TbSysUsers> userMap = new HashMap<String, TbSysUsers>();
	      	String userCode = null;
	      	for (TbSysUsers tbSysUsers : users) {
	      		userCode = tbSysUsers.getUserCode();
	      		if (!userMap.containsKey(userCode)) {
	      			userMap.put(userCode, tbSysUsers);
	      		}
	      	}
	      	
	      	for (String LNAME : map.keySet()) {
      			Map<String, String> user = map.get(LNAME);
      			//
      			TbSysUsers tbSysUsers = null;
	      		if (userMap.containsKey(LNAME)) {
	      			tbSysUsers = userMap.get(LNAME);
	      		} else {
	      			tbSysUsers = new TbSysUsers();
	      		}
      			//
      			tbSysUsers.setUserCode(LNAME);
      			tbSysUsers.setUserName(user.get("UNAME"));
      			tbSysUsers.setUserPassword("123");
      			//
      			userService.save(tbSysUsers);
	      	}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	*//**
	 * 左侧导航菜单
	 * 
	 * @param
	 * @return
	 *//*
	@ResponseBody
	@RequestMapping("/navigation.do")
	public JSONObject navigation(HttpSession session, HttpServletRequest request,Integer userID) {


		List<String> menuIds = null;
		Integer userId = (Integer) request.getAttribute("userID");
		List<TbSysRoles> myRoles = UserService.getUserRoles(userID);
		menuIds = RoleService.getMenuList(myRoles.get(0).getPkRoleId());
		List<TbSysMenu> menuList = new ArrayList<TbSysMenu>();
		for (String menuId: menuIds) {
			menuList.add(menuService.getMenuById(menuId));
		}

		return navigationNotUseSSO(menuList);
	}
	
	private JSONObject navigationNotUseSSO(List<TbSysMenu> menuList) {
		// json格式
		JSONObject data = new JSONObject();
		data.put("resultcode", 200);
		data.put("reason", "获取菜单成功");
		// data的result属性的值
		List<Map<String, Object>> resultlist2 = new ArrayList<Map<String, Object>>();
		Map<String, Object> resultmap = null;
		Map<String, Object> resultmap2 = null;

//		// 查询level列为0的全部信息 ---为父节点
//		List<TbSysMenu> tdyalist = UserService.authoritiesfindAll(0);
		// 循环外层--父节点
		for (TbSysMenu list : menuList) {
			List<Map<String, Object>> resultlist3 = new ArrayList<Map<String, Object>>();
			resultmap = new HashMap<String, Object>();
			// 将父节点name属性存近map
			if(list.getParentAuthId()==0){
				resultmap.put("name", list.getMenuName());
			}else {
				continue;
			}

			// 循环内层与其父节点对应的子节点
			for (TbSysMenu list2 : menuList) {

				// 将子节点存进map2
				if(list2.getParentAuthId()==list.getPkMenuId()){
					resultmap2 = new HashMap<String, Object>();
					resultmap2.put("name", list2.getMenuName());
					resultmap2.put("url", list2.getPageUrl());
					resultlist3.add(resultmap2);
					resultmap.put("subMenu", resultlist3);
				}

			}
			// 将map存近List<map>
			resultlist2.add(resultmap);
		}
		// list<map>存进json
		data.put("result", resultlist2);
		return data;
	}*/
	


	/*@RequestMapping("/list.do")
	@ResponseBody
	public AjaxJson list(TbSysUsers tbSysUsers, Integer pagenum, Integer pagesize){
		HashMap<String, Object> map = new HashMap<>();
		AjaxJson ajaxJson = new AjaxJson();
		List<TbSysUsers> res = UserService.page(tbSysUsers,pagenum,pagesize);
		Integer count = UserService.getAllRowCount();
		map.put("dataList",res);
		map.put("total",count);
		ajaxJson.setResult(map);
		ajaxJson.setCode(101);
		ajaxJson.setMsg("success");
		return ajaxJson;
	}*/

	/**
	 * 用户列表
	 * @param tbSysUsers
	 * @param pagenum
	 * @param pagesize
     * @return
     */
	@RequestMapping("/list.do")
	@ResponseBody
	public AjaxJson list(TbSysUsers tbSysUsers, Integer pagenum, Integer pagesize){
		AjaxJson ajaxJson =UserService.getDataList(tbSysUsers,pagenum,pagesize);
		return ajaxJson;
	}

	/**
	 * 获取某个用户对应的roleUsers
	 *//*
	@RequestMapping("/getOneUserRoles.do")
	@ResponseBody
	public AjaxJson getRoleUsers(String uid){
		AjaxJson ajaxJson = new AjaxJson();
		List<TbSysRoles> list1=UserService.getUserRoles(uid);
		HashMap map=new HashMap();
		map.put("roleUserList",list1);
		ajaxJson.setResult(map);
		return ajaxJson;
	}*/

	/**
	 * 获取某个用户对应的roleUsers
	 */
	@RequestMapping("/getOneUserRoles.do")
	@ResponseBody
	public AjaxJson getRoleUsers(String uid){
		AjaxJson ajaxJson = new AjaxJson();
		ajaxJson=UserService.getRoleUsers(uid);
		return ajaxJson;
	}

	/**
	 * 用户信息
	 *//*
	@Log("用户信息")
	@RequestMapping("/info.do")
	public ModelAndView info(TbSysUsers tbSysUsers){
        HashMap<String,Object> map = new HashMap<>();
		TbSysUsers res = UserService.get(tbSysUsers.getPkUserId());
		if(res==null){
			res=new TbSysUsers();
		}
		map.put("user",res);
		return new ModelAndView("user/edit.html","map",map);
	}*/
	/**
	 * 用户信息
	 */
	@Log("用户信息")
	@RequestMapping("/info.do")
	public ModelAndView info(TbSysUsers tbSysUsers){
		HashMap<String,Object> map = new HashMap<>();
		TbSysUsers res = UserService.get(tbSysUsers.getPkUserId());
		if(res==null){
			res=new TbSysUsers();
		}
		map.put("user",res);
		return new ModelAndView("user/edit.html","map",map);
	}

	/**
	 * 添加用户跳转
	 */
	@RequestMapping("/add.do")
	public ModelAndView add(TbSysUsers tbSysUsers){
		List<TbSysRoles> rolesList = RoleService.page( new TbSysRoles(), 1, 1000);//假设不大于1000个角色
		return new ModelAndView("system/user/add","roles",rolesList);
	}

	/**
	 * 保存/修改  用户
	 *//*
	@RequestMapping("/saveOrUpdate.do")
	@ResponseBody
	public AjaxJson saveOrUpdate(TbSysUsers tbSysUsers, String[] roles, HttpServletRequest request){
		AjaxJson ajaxJson = new AjaxJson();
		String userId=(String) request.getSession().getAttribute("userId");
		String nowTime=StringUtil.getNowTime();
		if(tbSysUsers.getPkUserId()==null||"".equals(tbSysUsers.getPkUserId())){
			tbSysUsers.setPkUserId(null);
			tbSysUsers.setCreateTime(nowTime);
			tbSysUsers.setUpdateTime(nowTime);
			tbSysUsers.setCreateUser(userId);
			tbSysUsers.setUpdateUser(userId);
			UserService.save(tbSysUsers);
			if(roles!=null) {
				for (String id : roles) {
					TbSysRoleUser tbSysRoleUser =new TbSysRoleUser();
					String wdUser = UserService.getUserID(tbSysUsers.getUserName(), tbSysUsers.getUserPassword());
					tbSysRoleUser.setRoleId(id);
					tbSysRoleUser.setUserId(wdUser);
					tbSysRoleUser.setCreateTime(nowTime);
					tbSysRoleUser.setUpdateTime(nowTime);
					tbSysRoleUser.setCreateUser(userId);
					tbSysRoleUser.setUpdateUser(userId);
					UserService.saveRoleUser(tbSysRoleUser);
				}
			}
		}else {
			tbSysUsers.setUpdateUser(userId);
			UserService.update(tbSysUsers);
			UserService.deleteOneUserRoles(tbSysUsers.getPkUserId());
			if(roles!=null) {
				for (String id : roles) {
					TbSysRoleUser tbSysRoleUser =new TbSysRoleUser();
					tbSysRoleUser.setRoleId(id);
					tbSysRoleUser.setUserId(tbSysUsers.getPkUserId());
					tbSysRoleUser.setCreateUser(userId);
					tbSysRoleUser.setUpdateUser(userId);
					tbSysRoleUser.setCreateTime((nowTime));
					tbSysRoleUser.setUpdateTime(nowTime);
					UserService.saveRoleUser(tbSysRoleUser);
				}
			}
		}

		return ajaxJson;
	}*/
	/**
	 * 保存/修改  用户
	 */
	@RequestMapping("/saveOrUpdate.do")
	@ResponseBody
	public AjaxJson saveOrUpdate(TbSysUsers tbSysUsers, String[] roles, HttpServletRequest request){
		AjaxJson ajaxJson = new AjaxJson();
		ajaxJson= UserService.saveOrUpdate(tbSysUsers,roles,request);
		return ajaxJson;
	}

	/**
	 * 删除用户
	 */
	@RequestMapping("/delete.do")
	@ResponseBody
	public AjaxJson delete(TbSysUsers tbSysUsers){
		AjaxJson ajaxJson = UserService.deleteUser(tbSysUsers);
		return ajaxJson;
	}
	/**
	 * 重置密码
	 *//*
	@RequestMapping("/rePsd.do")
	@ResponseBody
	public AjaxJson rePsd(TbSysUsers tbSysUsers, HttpServletRequest request){
		String userId=(String) request.getSession().getAttribute("userId");
		String nowTime=StringUtil.getNowTime();
		AjaxJson ajaxJson = new AjaxJson();
		tbSysUsers = UserService.get(tbSysUsers.getPkUserId());
		tbSysUsers.setUserPassword("123");
		tbSysUsers.setUpdateUser(userId);
		tbSysUsers.setUpdateTime(nowTime);
		UserService.save(tbSysUsers);
		return ajaxJson;
	}*/
	/**
	 * 重置密码
	 */
	@RequestMapping("/rePsd.do")
	@ResponseBody
	public AjaxJson rePsd(TbSysUsers tbSysUsers, HttpServletRequest request){
		AjaxJson ajaxJson =UserService.rePsd(tbSysUsers,request);
		return ajaxJson;
	}

	/**
	 * 删除用户
	 *//*
	@RequestMapping("/deleteAll.do")
	@ResponseBody
	public AjaxJson deleteAll(TbSysUsers tbSysUsers, String[] ids){
		AjaxJson ajaxJson = new AjaxJson();
		tbSysUsers.setUserName("");
		UserService.deleteOneUserRoles(tbSysUsers.getPkUserId());
		UserService.delete(tbSysUsers.getPkUserId());
		return ajaxJson;
	}*/
}
